import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Popconfirm, Card } from 'antd';
import { history } from 'umi';
import { useState } from 'react';
import { ProFormSelect, ProFormText, ProFormDependency, QueryFilter } from '@ant-design/pro-form';
import React, { useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { list, updateStatus, updateTop } from './service';
import type { TableListItem, TableListPagination } from './data';
import { hospitalList, hospitalDeptlist } from '@/services/ant-design-pro/api';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [formData, setFormData] = useState<API.RuleListItem>({});
  const handle = async (record: API.RuleListItem[]) => {
    const hide = message.loading('正在处理');
    let item = { id: record.id };
    item.status = record.status == 1 ? 0 : 1;
    try {
      const response = await updateStatus(item);
      if (response.code == 200) {
        message.success('处理成功,即将刷新');
      } else {
        message.error('处理失败!');
      }
      hide();
      actionRef.current?.reloadAndRest?.();
    } catch (error) {
      hide();
      message.error('处理失败');
      return false;
    }
  };

  const handleTop = async (record: API.RuleListItem[]) => {
    const hide = message.loading('正在处理');
    let item = { id: record.id };
    item.isTop = record.isTop == 0 ? 1 : 0;
    try {
      const response = await updateTop(item);
      if (response.code == 200) {
        message.success('处理成功,即将刷新');
      } else {
        message.error('处理失败!');
      }
      hide();
      actionRef.current?.reloadAndRest?.();
    } catch (error) {
      hide();
      message.error('处理失败');
      return false;
    }
  };

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '医生ID',
      dataIndex: 'id',
      width: '100px',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '医生姓名',
      dataIndex: 'name',
      width: '150px',
    },
    {
      title: '职称',
      dataIndex: 'grade',
      hideInForm: true,
      hideInSearch: true,
      width: '150px',
    },
    {
      title: '第一执业地点',
      dataIndex: 'hospitalName',
      hideInForm: true,
      width: '150px',
    },
    {
      title: '科室',
      dataIndex: 'deptName',
      hideInForm: true,
      hideInSearch: true,
      width: '150px',
    },
    {
      title: '擅长',
      dataIndex: 'specialize',
      width: '350px',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '置顶状态',
      dataIndex: 'isTop',
      width: '100px',
      hideInForm: true,
      hideInSearch: true,
      render: (text, _, index) => {
        return text > 0 ? '已置顶' : '';
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: '100px',
      hideInForm: true,
      hideInSearch: true,
      render: (text, _, index) => {
        return text == 0 ? '启用' : '禁用';
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '150px',
      render: (_, record) => [
        <a
          key="eidt"
          onClick={() => {
            history.push('/doctor/doctor-detail?id=' + record.id);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="disabled"
          title={record.status == 0 ? '是否要禁用该医生？' : '是否要启用该医生?'}
          onConfirm={() => handle(record)}
        >
          <a>{record.status == 0 ? '禁用' : '启用'}</a>
        </Popconfirm>,
        <Popconfirm
          key="top"
          title={record.isTop > 0 ? '确定要取消置顶吗?' : '确定要置顶吗?'}
          onConfirm={() => handleTop(record)}
        >
          <a>{record.isTop > 0 ? '取消置顶' : '置顶'}</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <Card bordered={false}>
        <QueryFilter<{
          name: string;
          company: string;
        }>
          // span={4}
          onFinish={async (values) => {
            console.log(values);
            setFormData(values);
            actionRef.current?.reloadAndRest?.();
          }}
        >
          <ProFormText name="name" label="医生姓名" />
          <ProFormSelect
            width="md"
            name="hospital"
            label="医院"
            showSearch
            request={async ({ keyWords }) => {
              let query = {
                likeQuery: {
                  name: keyWords,
                },
                pageNum: 1,
                pageSize: 20,
              };
              return hospitalList(query).then(({ data }) => {
                return data.list.map((item) => {
                  return {
                    label: item.name,
                    value: item.id,
                  };
                });
              });
            }}
          />
          <ProFormDependency name={['hospital']}>
            {({ hospital }) => {
              return (
                <ProFormSelect
                  params={{
                    key: hospital,
                  }}
                  name="dept"
                  label="第一科室"
                  showSearch
                  // fieldProps={{
                  //   labelInValue: true,
                  // }}
                  request={async () => {
                    console.log('hospital', hospital);
                    let query = {
                      eqQuery: {
                        hospitalId: hospital,
                        level: 1,
                      },
                      pageNum: 1,
                      pageSize: 20,
                    };

                    // let arr = user.split('-');
                    return hospitalDeptlist(query).then(({ data }) => {
                      return data.list.map((item) => {
                        return {
                          label: item.name,
                          value: item.id,
                        };
                      });
                    });
                  }}
                />
              );
            }}
          </ProFormDependency>
          <ProFormDependency name={['dept']}>
            {({ dept }) => {
              return (
                <ProFormSelect
                  params={{
                    key: dept,
                  }}
                  label="第二科室"
                  name="deptSecond"
                  // fieldProps={{
                  //   labelInValue: true,
                  // }}
                  request={async () => {
                    // let arr = user.split('-');
                    console.log('parentId', dept);
                    let query = {
                      eqQuery: {
                        parentId: dept,
                      },
                      pageNum: 1,
                      pageSize: 20,
                    };
                    return hospitalDeptlist(query).then(({ data }) => {
                      return data.list.map((item) => {
                        return {
                          label: item.name,
                          value: item.id,
                        };
                      });
                    });
                  }}
                />
              );
            }}
          </ProFormDependency>
        </QueryFilter>
      </Card>{' '}
      <ProTable<TableListItem, TableListPagination>
        actionRef={actionRef}
        search={false}
        rowKey="id"
        // search={{
        //   labelWidth: 120,
        // }}
        headerTitle={
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              history.push('/doctor/doctor-detail');
            }}
          >
            <PlusOutlined /> 新增
          </Button>
        }
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params,
          sorter,
          filter,
        ) => {
          console.log(params, formData, filter);
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          let query = {
            likeQuery: {
              name: formData.name,
            },
            eqQuery: {
              hospitalId: formData.hospital,
              first_dept_id: formData.dept,
              second_dept_id: formData.deptSecond,
            },
            pageNum: params.current,
            pageSize: params.pageSize,
          };
          const msg = await list(query);
          if (msg.code == 200) {
            return {
              data: msg.data.records,
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: msg.message,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: msg.data.total,
            };
          } else {
          }
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default TableList;
